package com.lzk.system.service.impl;

import com.lzk.basic.service.impl.BaseServiceImpl;
import com.lzk.system.domain.Menu;
import com.lzk.system.mapper.MenuMapper;
import com.lzk.system.service.IMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@Service
public class MenuServiceImpl extends BaseServiceImpl<Menu> implements IMenuService {
    @Autowired
    private MenuMapper menuMapper;

    /**
     * 菜单树----无限极
     * @return
     */
    @Override
    public List<Menu> menuTree() {
        //1.查询所有数据，循环遍历放入map
        List<Menu> all = menuMapper.loadAll();
        HashMap<Long, Menu> map = new HashMap<>();
        for (Menu menu : all) {
            map.put(menu.getId(), menu);
        }
        //2.创建一个空的数组为部门树,将数据传给前端
        ArrayList<Menu> deptTree = new ArrayList<>();
        for (Menu menu : all) {//顶级部门
            if (menu.getParent_id() == null) {
                deptTree.add(menu);
            }else {//子部门就放入child_menu
                Long parent_id = menu.getParent_id();

                Menu parentMenu = map.get(parent_id);

                parentMenu.getChildren().add(menu);
            }
        }

        return deptTree;
    }

}
